package ch01;

/**
 * Write a method to replace all spaces in a string with'%20'. You may assume 
 * that the string has sufficient space at the end of the string to hold the 
 * additional characters, and that you are given the "true" length of the 
 * string. (Note: if implementing in Java, please use a character array so that
 * you can perform this operation in place.)
 * EXAMPLE
 * Input: "Mr John Smith
 * Output: "Mr%20Dohn%20Smith"
 * @author Xi Chen
 *
 */

public class ReplaceSpaces_04 {
	
	public static void replaceSpaces(char[] str, int len) {
		int cnt = 0;  // Count space
		for (int i = 0; i < len; i++) {
			if (str[i] == ' ') {
				cnt++;
			}
		}
		for (int i = len - 1; i >= 0; i--) {
			if (str[i] != ' ') {
				str[i + 2 * cnt] = str[i];
			} else {
				str[i + 2 * cnt] = '0';
				str[i + 2 * cnt - 1] = '2';
				str[i + 2 * cnt - 2] = '%';
				cnt--;
			}
		}
	}

	public static void main(String[] args) {
		char[] str = {'M', 'r', ' ', 'J', 'o', 'h', 'n', ' ', 'S', 
				'm', 'i', 't', 'h', ' ', 'X', ' ', ' ', ' ', ' ', ' ', ' ', 
				' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', };
		System.out.println(str);
		replaceSpaces(str, 15);
		System.out.println(str);
	}

}
